#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb
from MySQLdb.cursors import DictCursor
from config.cnf import DB_CONFIG 
import utils.log_utils as log

class DBUtils:
   
    def __init__(self):
        '''Initializes the database connection data.'''
        self.host = DB_CONFIG['HOST']
        self.user = DB_CONFIG['USER']
        self.passwd = DB_CONFIG['PASSWD']
        self.dbname = DB_CONFIG['DBNAME']
        self.port = DB_CONFIG['PORT']
        self.charset = DB_CONFIG['CHARSET']

    def connect(self):
        conn = MySQLdb.connect(host = self.host, user = self.user, passwd = self.passwd,
                db = self.dbname, port = self.port, charset = self.charset)
        return conn

    def close(self, conn, cur):
        try:
            if cur:
                cur.close()
            if conn:
                conn.close()
        except MySQLdb.Error, err:
            log.error(err) 


    def execute_dict(self, sql, params=()):
        ret, conn = {}, None 
        try:
            conn = self.connect()
            cur = conn.cursor(DictCursor)
            cur.execute(sql, params)
            conn.commit()
            ret = cur.fetchall()
        except MySQLdb.Error, err:
            log.error(err)
        finally:
            self.close(conn, cur)
        return ret 

    def execute(self, sql, params=()):
        ret, conn = (), None 
        try:
            conn = self.connect()
            cur = conn.cursor()
            cur.execute('SET NAMES utf8')
            cur.execute(sql, params)
            conn.commit()
            ret = cur.fetchall()
        except MySQLdb.Error, err:
            log.error(err)
        finally:
            self.close(conn, cur)
        return ret 

        
